# map_window.py
import json
import os

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QPushButton, QLineEdit, QHBoxLayout


class MapWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("AIS 船舶地图")
        self.setGeometry(100, 100, 800, 600)

        self.map_view = QWebEngineView()
        self.setCentralWidget(self.map_view)
        page = self.map_view.page()
        page.javaScriptConsoleMessage = lambda level, msg, line, source: print(f"[JS] {msg} (line {line})")

        self.map_data = []

        self.init_ui()
        self.map_view.setHtml(self.generate_map_html())

    def init_ui(self):
        layout = QVBoxLayout()

        header_layout = QHBoxLayout()

        mmsi_input = QLineEdit()
        setting_button = QPushButton("设置")
        setting_button.clicked.connect(lambda: self.set_highlight_mmsi(mmsi_input.text()))
        refresh_button = QPushButton("手动刷新")
        refresh_button.clicked.connect(self.update_map_from_cache)
        header_layout.addWidget(mmsi_input)
        header_layout.addWidget(setting_button)
        header_layout.addWidget(refresh_button)
        layout.addLayout(header_layout)
        layout.addWidget(self.map_view)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def generate_map_html(self):
        leaflet_dir = os.path.abspath("resources/leaflet")

        html = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>AIS 地图</title>
            <style>#map { height: 100%; }</style>
            <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.4/leaflet.min.css">
            <script src="https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
            <script>
            window.onerror = function(message, source, lineno, colno, error) {
                    console.error("JS 错误:", message, "at", source, "line", lineno);
                    return true;
                };
            </script>            
        </head>
        <body>
            <div id="map" style="height:100vh"></div>
            
            <script>
                var map = L.map('map').setView([30.0, 122.0], 14);
                L.tileLayer("https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",{
                            attribution: '&copy; 高德地图',
                            maxZoom: 18,
                            minZoom: 3,
                            subdomains: "1234",
                            zoom: 3
                        }).addTo(map);
                        
                var markers = {};
                var highlightMMSI = null;
                window.updateMap = function(dataArray) {                    
                    
                    dataArray.forEach(function(data){
                        if (!data.lat || !data.lon) return;
                                                
                        if (markers[data.mmsi]) {
                            map.removeLayer(markers[data.mmsi]);
                        }
                        
                        var isHighlight = highlightMMSI && data.mmsi === highlightMMSI;
                        var marker;
                        
                        if (isHighlight) {
                            marker = L.circleMarker([data.lat, data.lon], {
                                color: "#ff0000",
                                fillColor: "#ff0000",
                                fillOpacity: 0.7,
                                radius: 8
                            }).addTo(map);
                        }else {
                            marker = L.marker([data.lat, data.lon]).addTo(map)
                        }
                        
                        marker.bindPopup("<b>" + data.mmsi + "</b><br/>" +
                             "经纬度：" + data.lat.toFixed(5) + ", " + data.lon.toFixed(5) + "<br/>" +
                             "航速：" + data.speed + "节<br/>" +
                             "航向：" + data.course + "°");
                        markers[data.mmsi] = marker
                    });
                };
                
                // 设置要高亮的 MMSI
                window.setHighlightMMSI = function(mmsi) {
                    highlightMMSI = mmsi;
                };
            </script>
        </body>
        </html>
        """
        return html

    def update_map(self, ais_data_list):
        """直接更新地图（用于主程序主动推送）"""
        self.map_data = ais_data_list
        js_data = json.dumps(ais_data_list)
        js_code = f"if (window.updateMap) {{ window.updateMap({js_data}); }}"
        self.map_view.page().runJavaScript(js_code)

    def update_map_from_cache(self):
        """从缓存中读取最新数据并刷新地图"""
        if hasattr(self, 'map_data') and self.map_data:
            js_code = f"window.updateMap({self.map_data});"
            self.map_view.page().runJavaScript(js_code)

    def closeEvent(self, event):
        """关闭时停止定时器"""
        if hasattr(self, 'refresh_timer'):
            self.refresh_timer.stop()
        event.accept()

    def set_highlight_mmsi(self, mmsi):
        """设置要高亮的 MMSI"""
        js_code = f"if (window.setHighlightMMSI) {{ window.setHighlightMMSI('{mmsi}'); }}"
        self.map_view.page().runJavaScript(js_code)

